package org.formal.system.controller;


import java.util.List;
import javax.annotation.Resource;
import org.formal.common.controller.BaseController;
import org.formal.common.data.ResultData;
import org.formal.system.entity.ResourceEntity;
import org.formal.system.service.ResourceService;
import org.formal.system.shiro.manager.ShiroService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 资源控制类
 * @author jiangyan
 *
 */
@RestController
@RequestMapping(value = "/resource")
public class ResourceController extends BaseController<ResourceEntity> {
	
	@Resource
	private ResourceService resourceService;
	
	@Resource
	private ShiroService shiroService;
	/**
	 * 
	 * 添加数据获取父级id 如果为不为空并且为叶子节点 修改isLeaf 为false 
	 * 否则将当前节点作为最顶级（0）同时修改当前节点为叶子节点
	 * 如果id不为空默认是需要递归修改子节点的层级
	 */
	@RequestMapping(value="/save") 
	@Override
	public ResultData saveEntity(ResourceEntity entity) {
		//节点原有 父级id存在 且出了节点之外不存在其他节点 修改父节点状态为叶子节点
		ResultData resultData;
		try {
			resourceService.saveWithUpdateStatus(entity);
			shiroService.updatePermission();
			resultData = this.getResultData(true, "保存成功");
		} catch (Exception e) {
			resultData = this.getResultData(false, "保存失败");
		}
		return resultData;
	}
	
	/**
	 * 保存角色及关联资源
	 * @param id 角色id
	 * @param resourceIds 资源集合
	 * @return
	 */
	@RequestMapping(value="/saveRoleResource")
	public ResultData saveRoleResource(String id, String resourceIds) {
		ResultData resultData;
		try {
			String [] resourceArray = resourceIds.split(",");
			this.resourceService.saveRoleResource(id,resourceArray);
			resultData = this.getResultData(true, "配置成功");
		}catch (Exception e) {
			resultData = this.getResultData(false, "配置失败");
		}
		return resultData;
	}
	
	/**
	 * 先根据当前节点id删除节点
	 * 同时判断父节点是否还存在子节点，不存在修改IsLeaf 为true 叶子节点
	 * 同时递归删除当前节点下的子节点
	 */
	@Override
	@RequestMapping(value="delete")
	public ResultData delete(String id) {
		ResultData resultData = null;
		try {
			this.resourceService.deleteWithChildrenById(id);
			resultData = this.getResultData(true, "删除成功");
		}catch (Exception e) {
			resultData = this.getResultData(false, "删除失败");
		}
		return resultData;
	}
	
	/**
	 * 根据角色获取资源
	 * @param roleId
	 * @return
	 */
	@RequestMapping(value="list/roleId")
	public List<ResourceEntity> getListByRoleId(String roleId){
		return this.resourceService.getListByRoleId(roleId);
	}
	
	/**
	 * 获取除本身资源节点及子节点数据
	 */
	@RequestMapping(value="list/excludeNode")
	public List<ResourceEntity> getExcludeNodes(String resourceId){
		List<ResourceEntity> resourceList = this.resourceService.getExcludeResources(resourceId);
		return resourceList;
	}

}
